/*
 *所有关于zm_data_record类的业务代码应在此处编写
*可使用repository.调用常用方法，获取EF/Dapper等信息
*如果需要事务请使用repository.DbContextBeginTransaction
*也可使用DBServerProvider.手动获取数据库相关信息
*用户信息、权限、角色等使用UserContext.Current操作
*zm_data_recordService对增、删、改查、导入、导出、审核业务代码扩展参照ServiceFunFilter
*/
using Dapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using VOL.AppManager.IRepositories;
using VOL.Core.Extensions;
using VOL.Core.ManageUser;
using VOL.Core.Utilities;
using VOL.Entity.DomainModels;
using VOL.Entity.ResDto;
using VOL.Entity.新文件夹;

namespace VOL.AppManager.Services
{
    public partial class zm_data_recordService
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly Izm_data_recordRepository _repository;//访问数据库

        [ActivatorUtilitiesConstructor]
        public zm_data_recordService(
            Izm_data_recordRepository dbRepository,
            IHttpContextAccessor httpContextAccessor
            )
        : base(dbRepository)
        {
            _httpContextAccessor = httpContextAccessor;
            _repository = dbRepository;
            //多租户会用到这init代码，其他情况可以不用
            //base.Init(dbRepository);
        }
        WebResponseContent webResponse = new WebResponseContent();


        public PageGridData<zmdatarecorddto> GetData(zmdatarecordQuery options)
        {
            DynamicParameters sqlParams = new DynamicParameters();

            string role_id = UserContext.Current.RoleId + "";

            string sql = "   select row_number() OVER () AS idx,  *,case when shzt is null then '未审核' when shzt=0 then '不通过'  when shzt=1 then '已通过' end shztname  from ( select userid, '" + role_id + "' role_id,case when submit_state='0'  then '未提交' else '已提交' end submit_state,  shzt ,sqcs ,b.id,a.id as data_id,a.projectname,jycs,TO_CHAR(xxtj_time,'YYYY-MM-DD') xxtj_time,case when xxtj_state is null and shzt=1 then '正在提交中' when xxtj_state=1 then '已通过'   end xxtj_state ,case when accept_state is null and xxtj_state=1 then '正在验收中' when accept_state=0 then '不通过'  when accept_state=1 then '已通过' end accept_state  ,TO_CHAR(a.create_time, 'YYYY-MM-DD HH24:MI:ss') create_time,TO_CHAR(sh_time, 'YYYY-MM-DD HH24:MI:ss') sh_time,sh_name,a.xzqdm,a.xzqname,a.provmc,a.provcode,a.citydm,a.citymc  from zm_data_record a left  join   zm_data_record_auditing b on a.id=b.data_id where 1=1 order by a.create_time desc ) t where 1=1  ";
            string sqlcount = "     select  count(1)  from zm_data_record a left  join   zm_data_record_auditing b on a.id=b.data_id where 1=1 ";

            if (options.sq_sj != null && options.sq_sj.Count == 2)
            {
                var start_time = Convert.ToDateTime(options.sq_sj[0] + "").AddDays(1).ToString("yyyy/MM/dd") + "";
                var end_time = Convert.ToDateTime(options.sq_sj[1] + "").AddDays(1).ToString("yyyy/MM/dd") + "";
                //sj = sj.AddMinutes(59);
                //sj = sj.AddSeconds(59);
                sqlcount += " and date(a.create_time) between '" + start_time + " 00:00:00' and '" + end_time + "  23:59:59'  ";
                sql += " and date(create_time) between '" + start_time + " 00:00:00' and '" + end_time + " 23:59:59'  ";

            }
            if (options.sh_sj != null && options.sh_sj.Count == 2)
            {
                var start_time = Convert.ToDateTime(options.sh_sj[0] + "").AddDays(1).ToString("yyyy/MM/dd") + "";
                var end_time = Convert.ToDateTime(options.sh_sj[1] + "").AddDays(1).ToString("yyyy/MM/dd") + "";
                sqlcount += " and date(sh_time)  between '" + start_time + " 00:00:00' and '" + end_time + "  23:59:59'  ";
                sql += " and date(sh_time)  between '" + start_time + " 00:00:00' and '" + end_time + "  23:59:59'  ";
            }
            if (options.shzt != null)
            {
                if (options.shzt == -1)
                {
                    sqlcount += " and shzt is null  ";
                    sql += " and shzt is null  ";
                }
                else if (options.shzt == 0)
                {
                    sqlcount += " and shzt='" + options.shzt + "'";
                    sql += "  and shzt='" + options.shzt + "'";
                }
                else if (options.shzt == 1)
                {
                    sqlcount += " and shzt='" + options.shzt + "'";
                    sql += " and shzt='" + options.shzt + "'";
                }
            }
            if (options.submit_state != null)
            {
                sqlcount += " and submit_state= " + options.submit_state;
                sql += " and submit_state=" + options.submit_state;

            }
            if (!string.IsNullOrEmpty(options.xzqdm))
            {

                sqlcount += " and a.xzqdm='" + options.xzqdm + "'";
                sql += " and xzqdm='" + options.xzqdm + "'";
            }
            if (!string.IsNullOrEmpty(options.citydm))
            {
                sqlcount += " and a.citydm='" + options.citydm + "'";
                sql += " and citydm='" + options.citydm + "'";
            }
            if (!string.IsNullOrEmpty(options.provcode))
            {

                sqlcount += " and a.provcode='" + options.provcode + "'";
                sql += " and provcode='" + options.provcode + "'";
            }

            //if (!string.IsNullOrEmpty(options.userid))
            //{
            //    sqlcount += " and userid='" + options.userid + "'";
            //    sql += " and userid='" + options.userid + "'";
            //}

            sql += "  limit " + options.pagesize + " offset (" + options.pageindex + "-1)*  " + options.pagesize;
            var datacount = repository.DapperContext.ExecuteScalar(sqlcount, sqlParams).GetInt();
            var data = repository.DapperContext.QueryList<zmdatarecorddto>(sql, sqlParams).ToList();
            int totalPages = datacount / options.pagesize;
            if (datacount % options.pagesize != 0)
            {
                totalPages++;
            }
            return new PageGridData<zmdatarecorddto> { rows = data, status = 0, total = datacount, summary = new { pagecount = totalPages } };
        }


        /// <summary>
        /// 新建
        /// </summary>
        /// <param name="saveDataModel"></param>
        /// <returns></returns>
        public override WebResponseContent Add(SaveModel saveDataModel)
        {
            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            string submit_state = saveDataModel.MainData.DicKeyIsNullOrEmpty("submit_state") + "";
            AddOnExecute = (SaveModel saveModel) =>
            {
                //如果返回false,后面代码不会再执行
                return webResponse.OK();
            };
            // 在保存数据库前的操作，所有数据都验证通过了，这一步执行完就执行数据库保存
            var sys_user = _repository.DapperContext.QueryList<Sys_User>("select * from sys_user where \"User_Id\"=@id", new { id = UserContext.Current.UserId }).FirstOrDefault();

            AddOnExecuting = (zm_data_record order, object list) =>
            {

                int num = 0;
                string dm = "";
                zm_data_record model = null;
                zm_data_record_auditing item = null;
                if (!string.IsNullOrEmpty(sys_user.Xzqdm + ""))
                {
                    dm = sys_user.Xzqdm + "";
                    model = _repository.DapperContext.QueryList<zm_data_record>("select * from zm_data_record where submit_state='0' and \"xzqdm\"=@Xzqdm", new { Xzqdm = dm }).FirstOrDefault();
                    item = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  \"xzqdm\"=@Xzqdm order by sh_time desc LIMIT 1 ", new { Xzqdm = dm }).FirstOrDefault();

                }
                else if (!string.IsNullOrEmpty(sys_user.CityDm))
                {
                    dm = sys_user.CityDm;
                    model = _repository.DapperContext.QueryList<zm_data_record>("select * from zm_data_record where submit_state='0' and \"citydm\"=@citydm", new { citydm = dm }).FirstOrDefault();
                    item = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  \"citydm\"=@citydm order by sh_time desc LIMIT 1 ", new { citydm = dm }).FirstOrDefault();

                }
                if (model != null)
                {
                    string sql = "delete from zm_data_record where id='" + model.id + "' ";

                    int c = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);
                }


                if (order.submit_state == "1")
                {
                    if (item != null)
                    {
                        if (item.ssfa_sh_state == 0 && string.IsNullOrEmpty(order.ssfa_name))
                        {
                            return webResponse.Error("请上传相关实施方案！");
                        }
                        if (UserContext.Current.RoleId != 1)
                        {
                            if (item.zjbg_sh_state == 0 && string.IsNullOrEmpty(order.zjbg_name))
                            {
                                return webResponse.Error("请上传相关技术总结报告！");
                            }
                        }
                    }
                    else
                    {
                        if (UserContext.Current.RoleId == 1)
                        {
                            if (string.IsNullOrEmpty(order.ssfa_name))
                            {
                                return webResponse.Error("请上传相关实施方案！");
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(order.ssfa_name) && string.IsNullOrEmpty(order.zjbg_name))
                            {
                                return webResponse.Error("请上传相关实施方案或技术总结报告！");
                            }
                        }
                    }




                    if (UserContext.Current.RoleId == 137)
                    {
                        if (item != null)
                        {
                            if (item.djsjy_sh_state == 0 && string.IsNullOrEmpty(order.djsjy_name))
                            {
                                return webResponse.Error("请上传相关接边记录表！");
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(order.djsjy_name))
                            {
                                return webResponse.Error("请上传相关接边记录表！");
                            }
                        }
                    }
                }
                order.xzqdm = sys_user.Xzqdm;
                order.xzqname = sys_user.XzqName;
                order.citydm = sys_user.CityDm;
                order.citymc = sys_user.CityMC;
                order.provcode = sys_user.ProvCode;
                order.provmc = sys_user.ProvMc;
                var count = 0;
                if (!string.IsNullOrEmpty(order.xzqdm))
                {
                    count = repository.Find(c => c.xzqdm == order.xzqdm).Count();
                }
                else if (!string.IsNullOrEmpty(order.citydm))
                {
                    count = repository.Find(c => c.citydm == order.citydm).Count();
                }
                order.sqcs = count + 1;
                order.create_time = DateTime.Now;
                order.create_name = UserContext.Current.UserTrueName;
                order.userid = UserContext.Current.UserId.ToString();

                return webResponse.OK();
            };
            //此方法中已开启了事务，如果在此方法中做其他数据库操作，请不要再开启事务
            // 在保存数据库后的操作，此时已进行数据提交，但未提交事务，如果返回false，则会回滚提交
            AddOnExecuted = (zm_data_record order, object list) =>
            {
                string message = "保存成功！";
                if (order.submit_state == "1")
                {
                    string sql = "insert into zm_message(id,xzqdm,xzqmc,citydm,citymc,provmc,provdm,data_id,isread,create_time,create_name,message)values" +
                   "('" + Guid.NewGuid() + "','" + sys_user.Xzqdm + "','" + sys_user.XzqName + "','" + sys_user.CityDm + "','" + sys_user.CityMC + "','" + sys_user.ProvMc
                   + "','" + sys_user.ProvCode + "','" + order.id + "','0','" + DateTime.Now.ToString() + "','" + sys_user.UserTrueName + "','" + order.projectname + " 已提交，请注意审核！') ";

                    int c = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);

                    message = "提交成功！，预审意见将在一到两个工作日内完成预审并反馈结果！";
                }
                return webResponse.OK("" + message, order);
            };


            return base.Add(saveDataModel);
        }

        /// <summary>
        /// 编辑操作
        /// </summary>
        /// <param name="saveModel"></param>
        /// <returns></returns>
        public override WebResponseContent Update(SaveModel saveModel)
        {
            //注意：如果要给其他字段设置值，请在此处设置,如：（代码生成器上将字段编辑行设置为0，然后点生成model）
            //saveModel.MainData["字段"] = "值";
            var sys_user = _repository.DapperContext.QueryList<Sys_User>("select * from sys_user where \"User_Id\"=@id", new { id = UserContext.Current.UserId }).FirstOrDefault();

            //此处saveModel是从前台提交的原生数据，可对数据进修改过滤
            UpdateOnExecute = (SaveModel model) =>
            {
                return webResponse.OK();
            };

            //编辑方法保存数据库前处理
            UpdateOnExecuting = (zm_data_record order, object addList, object updateList, List<object> delKeys) =>
            {
                zm_data_record_auditing item = null;
                string dm = "";
                if (!string.IsNullOrEmpty(sys_user.Xzqdm + ""))
                {
                    dm = sys_user.Xzqdm + "";
                    item = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  \"xzqdm\"=@Xzqdm order by sh_time desc LIMIT 1 ", new { Xzqdm = dm }).FirstOrDefault();

                }
                else if (!string.IsNullOrEmpty(sys_user.CityDm))
                {
                    dm = sys_user.CityDm;
                    item = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  \"citydm\"=@citydm order by sh_time desc LIMIT 1 ", new { citydm = dm }).FirstOrDefault();

                }
                var zm_data_record = _repository.DapperContext.QueryList<zm_data_record>("select * from zm_data_record where \"id\"=@id", new { id = order.id }).FirstOrDefault();
                if (zm_data_record != null)
                {
                    if (order.submit_state == "0")
                    {
                        if (string.IsNullOrEmpty(order.ssfa))
                        {
                            order.ssfa = zm_data_record.ssfa;
                        }
                        if (string.IsNullOrEmpty(order.jcbg))
                        {
                            order.jcbg = zm_data_record.jcbg;
                        }
                        if (string.IsNullOrEmpty(order.zjbg))
                        {
                            order.zjbg = zm_data_record.zjbg;
                        }
                        if (string.IsNullOrEmpty(order.yj_file_path))
                        {
                            order.yj_file_path = zm_data_record.yj_file_path;
                        }
                        if (string.IsNullOrEmpty(order.lj_file_path))
                        {
                            order.lj_file_path = zm_data_record.lj_file_path;
                        }

                        if (string.IsNullOrEmpty(order.wydcjl))
                        {
                            order.wydcjl = zm_data_record.wydcjl;
                        }
                        if (string.IsNullOrEmpty(order.jjbg))
                        {
                            order.jjbg = zm_data_record.jjbg;
                        }

                        if (string.IsNullOrEmpty(order.djsjy))
                        {
                            order.djsjy = zm_data_record.djsjy;
                        }
                        if (string.IsNullOrEmpty(order.wth))
                        {
                            order.wth = zm_data_record.wth;
                        }
                        if (string.IsNullOrEmpty(order.cyd))
                        {
                            order.cyd = zm_data_record.cyd;
                        }
                        if (string.IsNullOrEmpty(order.chzlyy))
                        {
                            order.chzlyy = zm_data_record.chzlyy;
                        }
                        if (string.IsNullOrEmpty(order.ssfa_name))
                        {
                            order.ssfa_name = zm_data_record.ssfa_name;
                        }
                        if (string.IsNullOrEmpty(order.jcbg_name))
                        {
                            order.jcbg_name = zm_data_record.jcbg_name;
                        }
                        if (string.IsNullOrEmpty(order.zjbg_name))
                        {
                            order.zjbg_name = zm_data_record.zjbg_name;
                        }
                        if (string.IsNullOrEmpty(order.yj_file_name))
                        {
                            order.yj_file_name = zm_data_record.yj_file_name;
                        }
                        if (string.IsNullOrEmpty(order.lj_file_name))
                        {
                            order.lj_file_name = zm_data_record.lj_file_name;
                        }

                        if (string.IsNullOrEmpty(order.wydcjl_name))
                        {
                            order.wydcjl_name = zm_data_record.wydcjl_name;
                        }
                        if (string.IsNullOrEmpty(order.jjbg_name))
                        {
                            order.jjbg_name = zm_data_record.jjbg_name;
                        }

                        if (string.IsNullOrEmpty(order.djsjy_name))
                        {
                            order.djsjy_name = zm_data_record.djsjy_name;
                        }
                        if (string.IsNullOrEmpty(order.wth_name))
                        {
                            order.wth_name = zm_data_record.wth_name;
                        }
                        if (string.IsNullOrEmpty(order.cyd_name))
                        {
                            order.cyd_name = zm_data_record.cyd_name;
                        }
                        if (string.IsNullOrEmpty(order.chzlyy_name))
                        {
                            order.chzlyy_name = zm_data_record.chzlyy_name;
                        }

                        //if (string.IsNullOrEmpty(order.yj_file_name))
                        //{
                        //    order.yj_file_name = zm_data_record.yj_file_name;
                        //}
                        //if (string.IsNullOrEmpty(order.yj_file_path))
                        //{
                        //    order.yj_file_path = zm_data_record.yj_file_path;
                        //}
                        //if (string.IsNullOrEmpty(order.lj_file_path))
                        //{
                        //    order.lj_file_path = zm_data_record.lj_file_path;
                        //}
                        //if (string.IsNullOrEmpty(order.lj_file_name))
                        //{
                        //    order.lj_file_name = zm_data_record.lj_file_name;
                        //}

                    }
                    else
                    {

                        if (string.IsNullOrEmpty(order.ssfa))
                        {
                            order.ssfa = zm_data_record.ssfa;
                            order.ssfa_name = zm_data_record.ssfa_name;
                            if (string.IsNullOrEmpty(order.ssfa))
                            {
                                return webResponse.Error("请上传相关实施方案文件！");
                            }
                        }



                        if (string.IsNullOrEmpty(order.jcbg))
                        {
                            order.jcbg = zm_data_record.jcbg;
                            order.jcbg_name = zm_data_record.jcbg_name;
                            if (UserContext.Current.RoleId != 1)
                            {
                                if (string.IsNullOrEmpty(order.jcbg))
                                {
                                    return webResponse.Error("请上传相关检查报告！");
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(order.zjbg))
                        {
                            order.zjbg = zm_data_record.zjbg;
                            order.zjbg_name = zm_data_record.zjbg_name;
                            if (UserContext.Current.RoleId != 1)
                            {
                                if (string.IsNullOrEmpty(order.zjbg))
                                {
                                    return webResponse.Error("请上传相关技术总结报告！");
                                }
                            }
                        }



                        if (string.IsNullOrEmpty(order.yj_file_name))
                        {
                            order.yj_file_name = zm_data_record.yj_file_name;
                            order.yj_file_path = zm_data_record.yj_file_path;
                        }

                        if (string.IsNullOrEmpty(order.lj_file_name))
                        {
                            order.lj_file_name = zm_data_record.lj_file_name;
                            order.lj_file_path = zm_data_record.lj_file_path;
                        }



                        if (string.IsNullOrEmpty(order.wydcjl))
                        {
                            order.wydcjl = zm_data_record.wydcjl;
                            order.wydcjl_name = zm_data_record.wydcjl_name;
                            if (UserContext.Current.RoleId != 1)
                            {
                                if (string.IsNullOrEmpty(order.wydcjl))
                                {
                                    return webResponse.Error("请上传相关外业调查核查记录表！");
                                }
                            }
                        }

                        if (string.IsNullOrEmpty(order.jjbg))
                        {
                            order.jjbg = zm_data_record.jjbg;
                            order.jjbg_name = zm_data_record.jjbg_name;
                            if (UserContext.Current.RoleId != 1)
                            {
                                if (string.IsNullOrEmpty(order.jjbg))
                                {
                                    return webResponse.Error("请上传相关机检记录报告！");
                                }
                            }
                        }

                        //if (string.IsNullOrEmpty(order.wth))
                        //{
                        //    order.wth = zm_data_record.wth;
                        //    order.wth_name = zm_data_record.wth_name;
                        //    if (UserContext.Current.RoleId != 1)
                        //    {
                        //        if (string.IsNullOrEmpty(order.wth))
                        //        {
                        //            return webResponse.Error("请上传相关委托函！");
                        //        }
                        //    }
                        //}

                        if (string.IsNullOrEmpty(order.cyd))
                        {
                            order.cyd = zm_data_record.cyd;
                            order.cyd_name = zm_data_record.cyd_name;
                            if (UserContext.Current.RoleId != 1)
                            {
                                if (string.IsNullOrEmpty(order.cyd))
                                {
                                    return webResponse.Error("请上传相关抽样单！");
                                }
                            }
                        }

                        if (string.IsNullOrEmpty(order.chzlyy))
                        {
                            order.chzlyy = zm_data_record.chzlyy;
                            order.chzlyy_name = zm_data_record.chzlyy_name;
                            if (UserContext.Current.RoleId != 1)
                            {
                                if (string.IsNullOrEmpty(order.chzlyy))
                                {
                                    return webResponse.Error("请上传相关测绘资料交验移交清单！");
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(order.djsjy))
                        {
                            order.djsjy = zm_data_record.djsjy;
                            order.djsjy_name = zm_data_record.djsjy_name;
                        }
                    }
                    if (string.IsNullOrEmpty(order.xzqdm))
                    {
                        order.xzqdm = zm_data_record.xzqdm;
                        order.xzqname = zm_data_record.xzqname;
                    }
                    if (string.IsNullOrEmpty(order.citydm))
                    {
                        order.citydm = zm_data_record.citydm;
                        order.citymc = zm_data_record.citymc;
                    }
                    if (string.IsNullOrEmpty(order.provcode))
                    {
                        order.provcode = zm_data_record.provcode;
                        order.provmc = zm_data_record.provmc;
                    }


                    order.create_time = DateTime.Now;
                }
                else
                {
                    Add(saveModel);
                }

                return webResponse.OK();
            };

            //编辑方法保存数据库后处理
            //此方法中已开启了事务，如果在此方法中做其他数据库操作，请不要再开启事务
            // 在保存数据库后的操作，此时已进行数据提交，但未提交事务，如果返回false，则会回滚提交
            UpdateOnExecuted = (zm_data_record order, object addList, object updateList, List<object> delKeys) =>
            {
                string message = "保存成功！";
                if (order.submit_state == "1")
                {
                    //string update = "update zm_data_record set create_time='"+DateTime.Now+"' where id='"+order.id+"'";

                    //int n = _repository.DapperContext.ExcuteNonQuery(update, "", null, false);

                    string sql = "insert into zm_message(id,xzqdm,xzqmc,citydm,citymc,provmc,provdm,data_id,isread,create_time,create_name,message)values" +
                   "('" + Guid.NewGuid() + "','" + sys_user.Xzqdm + "','" + sys_user.XzqName + "','" + sys_user.CityDm + "','" + sys_user.CityMC + "','" + sys_user.ProvMc
                   + "','" + sys_user.ProvCode + "','" + order.id + "','0','" + DateTime.Now.ToString() + "','" + sys_user.UserTrueName + "','" + order.projectname + " 已提交，请注意审核！') ";

                    int c = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);

                    message = "提交成功！，预审意见将在一到两个工作日内完成预审并反馈结果！";
                }
                return webResponse.OK("" + message);
            };

            return base.Update(saveModel);
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="keys">删除的行的主键</param>
        /// <param name="delList">删除时是否将明细也删除</param>
        /// <returns></returns>
        public override WebResponseContent Del(object[] keys, bool delList = false)
        {
            //删除前处理
            //删除的行的主键
            DelOnExecuting = (object[] _keys) =>
            {
                string sql = "delete from zm_data_record where id='" + _keys[0] + "' ";

                int c = _repository.DapperContext.ExcuteNonQuery(sql, "", null, false);

                return webResponse.OK();
            };
            //删除后处理
            //删除的行的主键
            DelOnExecuted = (object[] _keys) =>
            {


                return webResponse.OK();
            };
            return base.Del(keys, delList);
        }
        public WebResponseContent GetDetaileByID(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return webResponse.Error("id不能为空");
            }
            var thisdata = repository.Find(c => c.id == id).FirstOrDefault();
            zm_data_record_auditing lastaudit;
            zm_data_record lastlog;
            if (thisdata != null)
            {
                if (!string.IsNullOrEmpty(thisdata.xzqdm))
                {
                    lastaudit = repository.DapperContext.QueryList<zm_data_record_auditing>(" select * from zm_data_record_auditing where xzqdm=@xzqdm and shzt=0 order by sh_time desc limit 1 ", new { xzqdm = thisdata.xzqdm }).FirstOrDefault();

                }
                else
                {
                    lastaudit = repository.DapperContext.QueryList<zm_data_record_auditing>(" select * from zm_data_record_auditing where citydm=@citydm and shzt=0 order by sh_time desc limit 1 ", new { citydm = thisdata.citydm }).FirstOrDefault();

                }
                if (lastaudit != null)
                {
                    lastlog = repository.Find(c => c.id == lastaudit.data_id).FirstOrDefault();
                }
                else
                {
                    lastlog = null;
                }
            }
            else
            {
                lastlog = null;
                lastaudit = null;
            }
            return webResponse.OK("操作成功", new { thisdata, lastaudit, lastlog });
        }



        public WebResponseContent GetProjectCount(zmdatarecordQuery options)
        {
            string sql = "";
            string auditsql = "";
            if (!string.IsNullOrEmpty(options.xzqdm))
            {
                sql = " select * from zm_data_record where xzqdm=@key and submit_state='1'  ";
                auditsql = " select  * from zm_data_record_auditing where xzqdm=@key order by sh_time desc LIMIT 1; ";
            }
            else if (!string.IsNullOrEmpty(options.citydm) && string.IsNullOrEmpty(options.xzqdm))
            {
                sql = " select * from zm_data_record where citydm=@key  and (xzqdm is null or xzqdm='') and submit_state='1'  ";
                auditsql = " select  * from zm_data_record_auditing where citydm=@key  and (xzqdm is null or xzqdm='')  order by sh_time desc LIMIT 1; ";
            }
            var list = repository.DapperContext.QueryList<zm_data_record>(sql, new { key = options.key }).ToList();

            string projectname = options.projectname + "-2024年城市国土空间监测-第" + (list.Count + 1) + "次预审";

            var auditlist = repository.DapperContext.QueryList<zm_data_record_auditing>(auditsql, new { key = options.key }).ToList();


            return webResponse.OK("操作成功", new { list.Count, projectname, auditlist });
        }


        public WebResponseContent GetWorkUnitByState(zmdatarecordQuery options)
        {
            string sql = "";
            string data = "";
            string id = "";
            string rest = "";
            string dm = "";
            if (!string.IsNullOrEmpty(options.xzqdm))
            {
                sql = " select * from zm_data_record where xzqdm=@key and submit_state='0'    ";
                dm = options.xzqdm;
            }
            else if (!string.IsNullOrEmpty(options.citydm) && string.IsNullOrEmpty(options.xzqdm))
            {
                sql = " select * from zm_data_record where citydm=@key  and (xzqdm is null or xzqdm='') and submit_state='0'   ";
                dm = options.citydm;
            }
            var model = repository.DapperContext.QueryList<zm_data_record>(sql, new { key = dm }).FirstOrDefault();
            if (model == null)
            {
                if (!string.IsNullOrEmpty(options.xzqdm))
                {
                    sql = " select * from zm_data_record where xzqdm=@key and submit_state='1' and id not in(select data_id from zm_data_record_auditing where xzqdm=@key) ";
                }
                else if (!string.IsNullOrEmpty(options.citydm) && string.IsNullOrEmpty(options.xzqdm))
                {
                    sql = " select * from zm_data_record where citydm=@key and submit_state='1' and id not in(select data_id from zm_data_record_auditing where citydm=@key) ";
                } //sql = " select * from zm_data_record_auditing where xzqdm=@key and data_id='" + model.id + "'    ";
                var item = repository.DapperContext.QueryList<zm_data_record>(sql, new { key = dm }).FirstOrDefault();
                if (item != null)
                {
                    data = "【" + item.projectname + "】尚未审核，请先等待审核！";
                    rest = "1";
                }
            }
            else
            {
                data = "您有尚未提交的项目申请记录，是否清空重新进行申请？";
                id = model.id;
            }


            return webResponse.OK("操作成功", new { data, id, rest });
        }

        public WebResponseContent AdminGetDetaileByID(string id)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                return webResponse.Error("id不能为空");
            }
            zm_data_record_auditing nextAuditRecord = null;
            var thisdata = repository.Find(c => c.id == id).FirstOrDefault();
            if (thisdata != null)
            {
                string xzqdm = thisdata.xzqdm;
                nextAuditRecord = repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where data_id=@id ", new { @id = thisdata.id }).OrderByDescending(u => u.sh_time).FirstOrDefault();

            }




            zm_data_record_auditing thisaudit = null;
            if (thisdata != null)
            {
                thisaudit = repository.DapperContext.QueryList<zm_data_record_auditing>("select *from zm_data_record_auditing where data_id=@id", new { @id = thisdata.id }).FirstOrDefault();
            }

            zm_data_record_auditing lastitem = null;
            string dm = "";
            if (thisdata != null)
            {
                dm = thisdata.xzqdm;
                if (string.IsNullOrEmpty(dm))
                {
                    dm = thisdata.citydm;
                    lastitem = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  citydm=@dm order by sh_time desc LIMIT 1 ", new { dm = dm }).FirstOrDefault();

                }
                else
                {
                    lastitem = _repository.DapperContext.QueryList<zm_data_record_auditing>("select * from zm_data_record_auditing where  xzqdm=@dm order by sh_time desc LIMIT 1 ", new { dm = dm }).FirstOrDefault();

                }

            }

            return webResponse.OK("操作成功", new { thisdata, thisaudit, nextAuditRecord, lastitem });
        }
    }
}



